# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day20_游于艺.py
# @ Time: 2018/3/12 19:45

"""
主要是练习装饰器,和多线程,多进程的使用

使用装饰器增强完成1-999999所有奇数和计算10次
   1.使用普通方法
   2.使用多线程
   3.使用多进程
   4.采用线程池完成计算
   5.采用进程池完成计算
"""
from multiprocessing import Process,Pool,cpu_count
from multiprocessing.dummy import Pool as ThreadPool
from threading import Thread,current_thread
import time

def c_time(func):
    def inner(num1,num2):
        time1 = time.time()
        func(num1,num2)
        time2 = time.time()
        print("函数%s计算花费的时间为%s" % (func.__name_,str(time2-time1)))
    return inner

# 1.使用普通方法
@c_time
def sum_odd(min,max):
    for i in range(10):
        print(sum(range(min, max, 2)))

def sumOdd(min,max):
    print(sum(range(min, max, 2)))
# 2.使用多线程
@c_time
def thread_10time(num1,num2):
    for i in range(10):
        thr = Thread(target=sumOdd,args=(num1,num2))
        thr.start()
        thr.join()

# 3.使用多进程
@c_time
def process_10time(num1,num2):
    process_list = [Process(target=sumOdd,args=(num1,num2)) for i in range(10)]
    for process in process_list
        process.start()
        process.join()

    # for i in range(10):
    #     pro = Process(target=sumOdd,args=(num1,num2))
    #     pro.start()
    #     pro.join()

# 4.采用线程池完成计算
@c_time
def threadPool_10time(num1,num2):
    pools = ThreadPool(cpu_count())
    for i in range(10):
        pools.apply_async(sumOdd, (num1,num2))
    pools.close()
    pools.join()

# 5.采用进程池完成计算
@c_time
def processPool_10time(num1,num2):
    pools = Pool(cpu_count())
    for i in range(10):
        pools.apply_async(sumOdd, (num1,num2))
    # pools.map_async(sumOdd,[num for i in range(10)])    #用map来实现
    pools.close()
    pools.join()

if __name__ == "__main__":
    sum_odd(1,999999)   #普通计算

    thread_10time(1,999999)     #10线程计算
    threadPool_10time(1,999999)     #线程池计算

    process_10time(1,999999)    #10进程计算
    processPool_10time(1,999999)    #进程池计算